package com.mzpai.product.util;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.HttpURLConnection;
import java.net.URL;

import com.alibaba.fastjson.JSONObject;
import com.mzpai.product.constant.WXCommonConstants;

public class WxQrCodeUtil {
	
	//获取AccessToken路径
	private static final String AccessToken_URL = "https://api.weixin.qq.com/cgi-bin/token";
	
	//获取二维码路径 A接口，A接口，生成小程序码，可接受path参数较长，生成个数受限 10万个
    private static final String WxCode_A_URL= "https://api.weixin.qq.com/wxa/getwxacode";
    
	//获取二维码路径 B接口，生成小程序码，可接受页面参数较短，生成个数不受限
    private static final String WxCode_B_URL= "https://api.weixin.qq.com/wxa/getwxacodeunlimit";
    
	/**
	 * 自己测试
	 */
//	private static final String appId = "wx556f538db75f4685";
//	private static final String keysCer = "74072a6f86a3b9cf9c22dd0ebc9093c5";
	
	 /**
	  * 获取接口调用凭证access_token
	  */
	 public static String postToken(String appId, String appSecret) throws Exception {
	 
	         String requestUrl = AccessToken_URL+"?grant_type=client_credential&appid=" + appId + "&secret=" + appSecret;
	         URL url = new URL(requestUrl);
	         // 打开和URL之间的连接
	         HttpURLConnection connection = (HttpURLConnection) url.openConnection();
	         connection.setRequestMethod("POST");
	         // 设置通用的请求属性
	         connection.setRequestProperty("Content-Type", "application/json");
	         connection.setRequestProperty("Connection", "Keep-Alive");
	         connection.setUseCaches(false);
	         connection.setDoOutput(true);
	         connection.setDoInput(true);
	 
	         // 建立实际的连接
	         connection.connect();
	         // 定义 BufferedReader输入流来读取URL的响应
	         BufferedReader in;
	         if (requestUrl.contains("nlp"))
	             in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "GBK"));
	         else
	             in = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
	         StringBuilder result = new StringBuilder();
	         String getLine;
	         while ((getLine = in.readLine()) != null) {
	             result.append(getLine);
	         }
	         in.close();
	         JSONObject jsonObject = JSONObject.parseObject(result.toString());
	         return jsonObject.getString("access_token");
	 }
	 
	 
	 /**
	  * 生成微信小程序二维码
      *
	  * @param page
	  *         当前小程序相对页面 必须是已经发布的小程序存在的页面（否则报错），例如 pages/index/index, 根路径前不要填加 /,不能携带参数（参数请放在scene字段里），如果不填写这个字段，默认跳主页面
	  * @param scene
	  *         最大32个可见字符，只支持数字，大小写英文以及部分特殊字符：!#$&'()*+,/:;=?@-._~，其它字符请自行编码为合法字符（因不支持%，中文无法使用 urlencode 处理，请使用其他编码方式）
	  * @param accessToken
	  *         接口调用凭证
	  */
     public static InputStream generateQrCode(String page, String scene, String accessToken) {
	 
    	     InputStream in=null;
	         try {
	 
	             //调用微信接口生成二维码
	             URL url = new URL(WxCode_B_URL+"?access_token=" + accessToken);
	             HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
	             httpURLConnection.setRequestMethod("POST");// 提交模式
	             // conn.setConnectTimeout(10000);//连接超时 单位毫秒
	             // conn.setReadTimeout(2000);//读取超时 单位毫秒
	             // 发送POST请求必须设置如下两行
	             httpURLConnection.setDoOutput(true);
	             httpURLConnection.setDoInput(true);
	             // 获取URLConnection对象对应的输出流
	             PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
	             // 发送请求参数
	             JSONObject paramJson = new JSONObject();
	             //这就是你二维码里携带的参数 String型  名称不可变
	             paramJson.put("scene", scene);
	             //注意该接口传入的是page而不是path
	             paramJson.put("page", page);
	             //这是设置扫描二维码后跳转的页面
	             paramJson.put("width", 430);
	             paramJson.put("is_hyaline", false);
	             paramJson.put("auto_color", false);
	             //line_color生效
//	             paramJson.put("auto_color", false);
//	             JSONObject lineColor = new JSONObject();
//	             lineColor.put("r", 0);
//	             lineColor.put("g", 0);
//	             lineColor.put("b", 0);
//	             paramJson.put("line_color", lineColor);
	             
	             printWriter.write(paramJson.toString());
	             // flush输出流的缓冲
	             printWriter.flush();
	             
	             //开始获取数据
	             in=httpURLConnection.getInputStream();
	             
	            /* BufferedInputStream bis = new BufferedInputStream(in);
	             
	             OutputStream os = new FileOutputStream(new File(filePath));
	             
	             int len;
	             byte[] arr = new byte[1024];
	             while ((len = bis.read(arr)) != -1) {
	            	 System.out.println(len);
	                 os.write(arr, 0, len);
	                 os.flush();
	             }
	             os.close();*/
	         } catch (Exception e) {
	             e.printStackTrace();
	         }
	     return in;
     }
	
	 
	 public static void main(String[] args) throws Exception{
		 String token = postToken(WXCommonConstants.appId, WXCommonConstants.AppSecret);
		 System.out.println(token);
		//生成二维码
		 //https://mz.bianwaixingqiu.com/store/?invite=true&store=
//		 String scene="https://mz.bianwaixingqiu.com/store/?invite=true&store=3325"; 
//		 String scene="3717";
		 String scene="storeId=3717";
		/* InputStream in=generateQrCode("pages/store/storeDetail/storeDetail", scene, token);
		 //开始获取数据
         BufferedInputStream bis = new BufferedInputStream(in);
         
         OutputStream os = new FileOutputStream(new File("D://test//test3.jpg"));
         
         int len;
         byte[] arr = new byte[1024];
         while ((len = bis.read(arr)) != -1) {
        	 System.out.println(len);
             os.write(arr, 0, len);
             os.flush();
         }
         os.close();*/
//		generateQrCode("D:\\test\\test3.jpg", "pages/store/storeIndex/storeIndex", "aa=108&bb=2&cc=3", token);
		 generateQrCode("pages/store/storeIndex/storeIndex", "aa=108&bb=2&cc=3", token);
	 }
}
